package ex.recruit.action;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import modules.system.entity.Role;
import modules.system.entity.User;
import modules.system.entity.UserRoleRel;
import modules.system.service.RoleService;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.guinea.core.acegi.AcegiCacheManager;
import com.guinea.core.orm.BaseEntity;
import com.guinea.core.orm.Page;
import com.guinea.core.orm.PropertyFilter;
import com.guinea.core.service.CommonService;
import com.guinea.core.service.EntityService;
import com.guinea.core.utils.ServletUtils;
import com.guinea.core.web.BaseForm;
import com.guinea.core.web.StrutsEntityAction;

import ex.recruit.form.RecruitUserFormEx;
import ex.system.service.UserRoleRelServiceEx;
import ex.system.service.UserServiceEx;

public class RecruitUserActionEx extends StrutsEntityAction {
	UserServiceEx userServiceEx;

	RoleService roleService;

	UserRoleRelServiceEx userRoleRelServiceEx;

	AcegiCacheManager acegiCacheManager;

	CommonService commonService;
	String oldLoginName;

	public EntityService getEntityService() {
		return userServiceEx;
	}

	public UserServiceEx getUserServiceEx() {
		return userServiceEx;
	}

	public void setUserServiceEx(UserServiceEx userServiceEx) {
		this.userServiceEx = userServiceEx;
	}

	public RoleService getRoleService() {
		return roleService;
	}

	public void setRoleService(RoleService roleService) {
		this.roleService = roleService;
	}

	public UserRoleRelServiceEx getUserRoleRelServiceEx() {
		return userRoleRelServiceEx;
	}

	public void setUserRoleRelServiceEx(
			UserRoleRelServiceEx userRoleRelServiceEx) {
		this.userRoleRelServiceEx = userRoleRelServiceEx;
	}

	public CommonService getCommonService() {
		return commonService;
	}

	public void setCommonService(CommonService commonService) {
		this.commonService = commonService;
	}

	/**
	 * 列出所有对象的Action函数.
	 */
	public ActionForward list(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		// 从request中获取含属性前缀名的参数,构造去除前缀名后的参数Map.
		Map filterParamMap = ServletUtils.getParametersStartingWith(request,
				FILTER_PREFIX + "_");
		List filters = PropertyFilter.buildFromParaMap(filterParamMap);
		Page page = PropertyFilter.buildPageFromHttpRequest(request,
				REQUEST_PAGE);

		page = getEntityService().findPage(page, filters);

		request.setAttribute(REQUEST_PAGE, page);
		request.setAttribute(FILTER_MAP, filterParamMap);

		request.setAttribute("allRoles", getRoleService().get());
		return mapping.findForward(LIST);
	}

	/**
	 * 显示修改对象Form的Action函数.
	 */
	public ActionForward edit(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {

		bindForm(form, entity);
		if (id != null) {
			String[] relativeRoleIds = getUserServiceEx()
					.getRelativeRoleIds(id);
			RecruitUserFormEx userForm = (RecruitUserFormEx) form;
			userForm.setRelativeRoleIds(relativeRoleIds);
		}
		request.setAttribute("allRoles", getRoleService().get());
		return handleEdit(mapping, form, request, response);
	}

	protected void initProperties() {
		oldLoginName = null;
		super.initProperties();
	}

	protected void initFirst(ActionForm form, HttpServletRequest request) {
		findEntity(form, request);

		if (entity != null) {
			isCreateOperation = false;
			User user = (User) entity;
			if(form != null){
				BaseForm baseForm = (BaseForm) form;
				baseForm.setId(user.getId());
				form = baseForm;
			}
			id = user.getId();
			oldLoginName = user.getLoginName();
		} else {
			id = null;
		}
	}

	/**
	 * 初始化业务对象的函数.
	 */
	protected void doSaveEntity(HttpServletRequest request, ActionForm form) {
		String[] relativeRoleIds = request
				.getParameterValues("relativeRoleIds");
		// 如果是更新操作，先保存原来来的loginName

		super.doSaveEntity(request, form);
		User user = (User) entity;
		getUserRoleRelServiceEx().deleteByUserId(user.getId());

		boolean isConsoleUser = false;
		for (int i = 0; relativeRoleIds != null && i < relativeRoleIds.length; i++) {
			Long roleId = new Long(relativeRoleIds[i]);
			Role role = getRoleService().getRole(roleId);
			if (role != null) {
				String roleName = role.getRoleName();
				if ("role_console_user".equals(roleName)
						|| "role_recruit_admin".equals(roleName)
						|| "role_recruit_region_manager".equals(roleName)
						|| "role_recruit_read".equals(roleName)) {
					isConsoleUser = true;
				}
				UserRoleRel userRoleRel = new UserRoleRel();
				userRoleRel.setUser(user);
				userRoleRel.setRole(role);
				getUserRoleRelServiceEx().save(userRoleRel);
			}
		}

		// 如果是后台用户，需要修改广域网中的权限
		if (isConsoleUser) {
			if (oldLoginName != null
					&& getCommonService().isSkodxUserExists(oldLoginName))
				getCommonService().updateSkodxUser(oldLoginName,
						user.getLoginName(), user.getLoginPassword(),
						user.getOtherName());
			else if(getCommonService().isSkodxUserExists(user.getLoginName()))
				getCommonService().updateSkodxUser(user.getLoginName(),
						user.getLoginName(), user.getLoginPassword(),
						user.getOtherName());
			else
				getCommonService().addSkodxUser(user.getLoginName(),
						user.getLoginPassword(), user.getOtherName());
		}

		acegiCacheManager.refreshUserCache();
	}

	protected void doEraseEntity(HttpServletRequest request) {
		//如果是后台用户，先删除广域网中的权限
		User user = (User) entity;
		boolean isConsoleUser = false;
		for (Iterator iterator = user.getUserRoleRels().iterator(); iterator.hasNext();) {
			UserRoleRel userRoleRel = (UserRoleRel) iterator.next();
			Role role =userRoleRel.getRole();
			String roleName = role.getRoleName();
			if ("role_console_user".equals(roleName)
					|| "role_recruit_admin".equals(roleName)
					|| "role_recruit_region_manager".equals(roleName)
					|| "role_recruit_read".equals(roleName)) {
				isConsoleUser = true;
				break;
			}
		}
		if(isConsoleUser){
			getCommonService().deleteSkodxUser(user.getLoginName());
		}
		super.doEraseEntity(request);
	}

	public AcegiCacheManager getAcegiCacheManager() {
		return acegiCacheManager;
	}

	public void setAcegiCacheManager(AcegiCacheManager acegiCacheManager) {
		this.acegiCacheManager = acegiCacheManager;
	}

}
